package com.yztc.xiami_app.ui.fragment;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.yztc.xiami_app.R;
import com.yztc.xiami_app.adapter.homepage.GoodsAdapter;
import com.yztc.xiami_app.bean.goods.ADBean;
import com.yztc.xiami_app.bean.goods.BaseBean;
import com.yztc.xiami_app.bean.goods.GoodsBean;
import com.yztc.xiami_app.constant.OtherConstant;
import com.yztc.xiami_app.constant.URLConstant;
import com.yztc.xiami_app.helper.baidumap.ILocationListener;
import com.yztc.xiami_app.helper.baidumap.MapLocation;
import com.yztc.xiami_app.ui.activity.ReceiveAddressActivity;
import com.yztc.xiami_app.ui.activity.goodsdetails.GoodsDetailsActivity;
import com.yztc.xiami_app.ui.goods.interfaces.IGoodsItemClickListener;
import com.yztc.xiami_app.ui.goods.presenter.GoodsPresenter;
import com.yztc.xiami_app.ui.goods.presenter.GoodsPresenterImpl;
import com.yztc.xiami_app.ui.goods.view.IGoodsView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * A simple {@link Fragment} subclass.
 * <p>
 * “主页Fragment”
 */
public class HomePageFragment extends Fragment implements IGoodsView ,IGoodsItemClickListener{


    @BindView(R.id.toolbar_home_page)
    Toolbar toolBar; //"首页"的ToolBar
    @BindView(R.id.goods_list_recyclerView)
    RecyclerView goodsListRv; //显示商品列表的RecyclerView
    @BindView(R.id.edt_search)
    EditText searchEdt; //搜索的输入框
    @BindView(R.id.tv_location)
    TextView locationTv; //显示定位结果的文字

    private Context mContext;
    private GoodsAdapter mGoodsAdapter; //商品列表展示的适配器
    private List<BaseBean> mGoodsList = new ArrayList<>(); //商品列表的数据源
    private  GridLayoutManager layoutManager;
    private int mLastVisibleItem; //最后一个可见的Item的位置
    private int currentPage = 1; //当前页数
    //百度定位的回调接口
    private ILocationListener listener = new ILocationListener() {
        @Override
        public void getAddress(String address) {}

        @Override
        public void getCity(String city) {
            locationTv.setText(city); //设置定位的结果
        }
    };

    public HomePageFragment() {
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        mContext = getActivity();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        View view = inflater.inflate(R.layout.fragment_home_page, container, false);
        ButterKnife.bind(this, view);

        //展示商品列表的相关设置
        initGoodsRecyclerView();
        loadGoodsData(currentPage);

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        MapLocation location = new MapLocation(getActivity(),listener);
        location.getAddress(); //获取定位的数据,接口回调来接收
    }

    @Override
    public void onResume() {
        super.onResume();
        goodsListRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            //滑动状态改变
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if(newState == RecyclerView.SCROLL_STATE_IDLE &&
                        mLastVisibleItem == mGoodsAdapter.getItemCount() -1){
                    //当滑动到底部，且已经停止
                    currentPage++; //页数加1
                    loadGoodsData(currentPage); //重新加载数据
                }
            }

            //改变后
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //获取最后一个可见的Item的位置
                mLastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });

    }

    //加载商品数据
    private void loadGoodsData(int currentPage) {
        Map<String, Object> params = new HashMap<>();
        params.put(URLConstant.CURRPAGE, currentPage);
        params.put(URLConstant.PAGESIZE, 10);
        params.put(URLConstant.UNDERLINE, "1479291874069");
        GoodsPresenter goodsPresenter = new GoodsPresenterImpl(this);
        //获取商品列表的数据
        goodsPresenter.getGoodsData(params);
    }

    //显示商品列表数据
    @Override
    public void showGoodsData(GoodsBean goodsBean) {

        //RecyclerView加载商品列表资源
        List<GoodsBean.TopickusBean> topickus = goodsBean.getTopickus();
        for (int i = 0; i < topickus.size(); i++) {
            List<GoodsBean.TopickusBean.ItemsBean> itemsBeanList = topickus.get(i).getItems();
            for (int j=0;j<itemsBeanList.size();j++){
                GoodsBean.TopickusBean.ItemsBean itemsBean = itemsBeanList.get(j);
                itemsBean.setBean_type(2); //设置商品在RecyclerView中的类型为2
                mGoodsList.add(itemsBean);
            }
        }
        mGoodsAdapter.notifyDataSetChanged();
    }

    //初始化展示商品列表的RecyclerView
    private void initGoodsRecyclerView() {
        //初始化数据源，初始状态只有一个轮播的广告
        ADBean adBean = new ADBean();
        adBean.setBean_type(1);
        mGoodsList.add(adBean); //添加到数据源

        mGoodsAdapter = new GoodsAdapter(mContext, mGoodsList,this);
        layoutManager = new GridLayoutManager(mContext, 3, OrientationHelper.VERTICAL, false);
        //设置跨列的效果
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                //获取Item的类型
                int type = mGoodsAdapter.getItemViewType(position);
                if(type == 1){
                   //设置RecyclerView的Item的第一个Item跨3列,也就是轮播的图片
                   return  3;
               }else if(type == 2){
                    return 1;
                }
                return 0;
            }
        });
        goodsListRv.setAdapter(mGoodsAdapter);
        goodsListRv.setLayoutManager(layoutManager);
    }

    //点击定位结果的TextView，跳转到收货地址的Activity
    @OnClick(R.id.tv_location)
    public void onClick() {
        Intent intent = new Intent(mContext, ReceiveAddressActivity.class);
        startActivity(intent);
    }

    //处理商品对象的被点击事件
    @Override
    public void onGoodsItemClick(int productId) {
        Intent intent = new Intent(mContext, GoodsDetailsActivity.class);
        intent.putExtra(OtherConstant.KEY_PRODUCTID,productId);
        startActivity(intent);
    }


}
